<?php

namespace app\admin\controller;

use app\common\AdminController;
use \think\facade\Filesystem as Filesystem;
use app\admin\model\Fileslog as FileslogDB;

class Upload extends AdminController
{
    public function UploadFile()
    {
        $category = request()->post('category') ? request()->post('category') : 'default';
        $file = request()->file('file');
        $fileSize = 1024 * 1024 * 10;
        try {
            validate(['file' => 'fileSize:' . $fileSize . '|fileExt:jpg,png,mp4,avi,mov,flv,webm|fileMime:image/jpeg,image/png,video/mp4,video/x-msvideo,video/quicktime,video/x-flv,video/webm'])
                ->check(['file' => $file]);
        } catch (\think\exception\ValidateException $e) {
            return error($e->getMessage(), 500);
        }
        $domain = request()->domain();
        // 上传到本地服务器
        $savename = Filesystem::disk('public')->putFile($category, $file);
        if (!$savename) {
            return error("上传失败");
        } else {
            $url = Filesystem::getDiskConfig('public', 'url') . DIRECTORY_SEPARATOR . $savename;
            FileslogDB::create([
                'url' => $url,
                'category' => $category,
                'type' => $file->getMime(),
                "name" => $file->getOriginalName(),
                'create_by' => $this->userId,
                'sha1' => $file->hash('sha1'),
                'storage' => 'local'
            ]);
            return success("上传成功", ['url' => $domain . $url]);
        }
    }

    public function uploadEditorPhoto()
    {
        $post = request()->post();
        $category = 'editorImg';
        $file = request()->file('file');
        $fileSize = 1024 * 1024 * 10;
        try {
            validate(['file' => 'fileSize:' . $fileSize . '|fileExt:jpg,png|fileMime:image/jpeg,image/png'])
                ->check(['file' => $file]);
        } catch (\think\exception\ValidateException $e) {
            return error($e->getMessage());
        }
        $domain = request()->domain();
        // 上传到本地服务器
        $savename = Filesystem::disk('public')->putFile($category, $file);
        if (!$savename) {
            return [
                "errno" => 1,
                "message" => "上传失败",
            ];
        } else {
            $url = Filesystem::getDiskConfig('public', 'url') . DIRECTORY_SEPARATOR . $savename;
            FileslogDB::create([
                'url' => $url,
                'category' => $category,
                'type' => $file->getMime(),
                "name" => $file->getOriginalName(),
                'create_by' => $this->userId,
                'sha1' => $file->hash('sha1'),
                'storage' => 'local'
            ]);
            return [
                "errno" => 0,
                "data" => [
                    "url" => $domain . $url
                ]
            ];
        }
    }
}
